<template>
  <div class="task-box">
    <div p-5>
      <div class="task-box-top">
        <div class="task-box-top-tittle">{{ boxTittle }}</div>
      </div>
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <div class="task-info">
          <div class="taskBox-tittle">
            <div class="taskBox-tittle-left"></div>
            <div class="taskBox-tittle-right">任务信息</div>
          </div>
          <a-row :gutter="24">
            <a-col class="gutter-row" :span="8">
              <a-form-item label="检查类型" name="checkTypeId">
                <a-select
                  v-model:value="formState.checkTypeId"
                  placeholder="请选择检查类型"
                  :options="checkTypeOptions"
                  allowClear
                >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="主办人" name="userName" :labelCol="{ style: { width: '82px' } }">
                <a-select v-model:value="userName" placeholder="请选择主办人" :open="false">
                </a-select>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item
                label="
            协办人"
                name="organizerId"
                :labelCol="{ style: { width: '82px' } }"
              >
                <a-select
                  v-model:value="formState.organizerId"
                  placeholder="请选择协作人"
                  :options="organizerOptions"
                  allowClear
                ></a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div class="base-info">
          <div class="taskBox-tittle">
            <div class="taskBox-tittle-left"></div>
            <div class="taskBox-tittle-right">单位信息</div>
          </div>
          <a-row :gutter="24">
            <a-col class="gutter-row" :span="8">
              <a-form-item label="场所名称" name="placeName">
                <a-input
                  v-model:value="formState.openPlaceInfo.placeName"
                  placeholder="请输入场所名称"
                  autocomplete="off"
                  show-count
                  :maxlength="16"
                />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="住址" name="area">
                <a-cascader
                  v-model:value="formState.openPlaceInfo.area"
                  :options="addressOptions"
                  placeholder="请选择住址"
                  :fieldNames="areaFieldNames"
                />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="详细地址" name="address">
                <a-input
                  v-model:value="formState.openPlaceInfo.address"
                  placeholder="请输入详细地址"
                  autocomplete="off"
                  show-count
                  :maxlength="68"
                />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="场所类型" name="locationType">
                <a-select
                  v-model:value="formState.openPlaceInfo.locationType"
                  placeholder="请选择场所类型"
                  :options="locationOptions"
                  allowClear
                >
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </a-form>
    </div>
    <div class="bottomBox"></div>
    <div class="bottomBtns" style="z-index: 3">
      <a-space :size="12">
        <a-button @click="cacel" size="large">取消</a-button>
        <a-button type="primary" @click="onSubmit" size="large">保存</a-button>
      </a-space>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { useRoute } from 'vue-router';
  import { reactive, ref, toRaw, onMounted } from 'vue';
  import {
    getCheckType,
    getAreaList,
    saveTask,
    getPlaceType,
    taskInfo,
    updataTask,
  } from '@/api/administrative';
  import { getKeys } from '@/utils/common';
  import type { Rule } from 'ant-design-vue/es/form';
  import { message } from 'ant-design-vue';
  import router from '@/router';
  import { getInfo, organizerList } from '@/api/account';
  import { useTabsViewStore } from '@/store/modules/tabsView';
  const tabsViewStore = useTabsViewStore();
  const route = useRoute();

  const formRef = ref();
  const labelCol = {
    span: 4,
  };
  const wrapperCol = {
    span: 20,
  };
  const formState = reactive({
    checkTypeId: undefined, //检查类型
    checkTypeName: '', //检查类型名称
    organizerId: undefined, //协作人
    organizerName: '',
    openPlaceInfo: {
      placeName: '',
      countyCode: undefined,
      county: '',
      townCode: undefined,
      town: '',
      locationType: undefined,
      locationTypeName: '',
      area: [],
      address: '',
    },
  });

  const userName = ref();

  const organizerOptions = ref();

  const boxTittle = ref('新增任务');

  const validateArea = async (_rule: Rule, value: string) => {
    if (formState.openPlaceInfo.area?.length == 0) {
      return Promise.reject('请选择住址');
    } else {
      return Promise.resolve();
    }
  };

  const validatePlaceName = async (_rule: Rule, value: string) => {
    if (formState.openPlaceInfo.placeName == '') {
      return Promise.reject('请输入场所名称');
    } else {
      return Promise.resolve();
    }
  };

  const validateLocation = async (_rule: Rule, value: string) => {
    if (formState.openPlaceInfo.locationType == undefined) {
      return Promise.reject('请选择场所类型');
    } else {
      return Promise.resolve();
    }
  };

  const validateAddress = async (_rule: Rule, value: string) => {
    if (formState.openPlaceInfo.address == '') {
      return Promise.reject('请输入详细地址');
    } else {
      return Promise.resolve();
    }
  };

  const rules = {
    checkTypeId: [
      {
        required: true,
        message: '请选择检查类型',
        trigger: 'change',
      },
    ],
    organizerId: [
      {
        required: true,
        message: '请选择协办人',
        trigger: 'change',
      },
    ],
    placeName: [
      {
        required: true,
        validator: validatePlaceName,
        trigger: 'change',
      },
    ],
    area: [
      {
        required: true,
        validator: validateArea,
        trigger: 'change',
      },
    ],
    locationType: [
      {
        required: true,
        validator: validateLocation,
        trigger: 'change',
      },
    ],
    address: [
      {
        required: true,
        validator: validateAddress,
        trigger: 'change',
      },
    ],
  } as any;

  const cacel = () => {
    router.push({
      path: '/administrative/administrative/strative',
    });
  };

  const onSubmit = () => {
    formRef.value
      .validate()
      .then(async () => {
        if (formState.openPlaceInfo.area) {
          formState.openPlaceInfo.countyCode = formState.openPlaceInfo.area[0];
          formState.openPlaceInfo.county = getKeys(
            addressOptions.value,
            formState.openPlaceInfo.area[0],
            'name',
          ) as any;
          formState.openPlaceInfo.townCode = formState.openPlaceInfo.area[1];
          formState.openPlaceInfo.town = getKeys(
            addressOptions.value,
            formState.openPlaceInfo.area[1],
            'name',
          ) as any;
        }
        const location = locationOptions?.value.find(
          (item) => item.value == formState.openPlaceInfo.locationType,
        ).label;
        formState.openPlaceInfo.locationTypeName = location;

        if (route.query.id && route.query.placeId) {
          let params = {
            id: route.query.id,
            placeId: route.query.placeId,
            organizerId: formState.organizerId || '',
            organizerName: organizerOptions?.value.find(
              (item) => item.value == formState.organizerId,
            ).label,
            checkTypeId: formState.checkTypeId,
            checkTypeName: checkTypeOptions.value.find(
              (item) => item.value == formState.checkTypeId,
            ).label,
            openPlaceInfo: formState.openPlaceInfo,
          };
          const res = await updataTask(params);

          if (res.code == 0) {
            message.success('修改任务成功！');
            tabsViewStore.closeCurrentTabToUrl(route, '/administrative/administrative/strative');
          }
        } else {
          let params = {
            checkTypeId: formState.checkTypeId,
            checkTypeName: checkTypeOptions.value.find(
              (item) => item.value == formState.checkTypeId,
            ).label,
            organizerId: formState.organizerId || '',
            organizerName: organizerOptions?.value.find(
              (item) => item.value == formState.organizerId,
            ).label,
            openPlaceInfo: formState.openPlaceInfo,
          };
          const res = await saveTask(params);

          if (res.code == 0) {
            message.success('创建任务成功！');
            tabsViewStore.closeCurrentTabToUrl(route, '/administrative/administrative/strative');
          }
        }
      })
      .catch((error) => {
        console.log('error', error);
      });
  };
  const resetForm = () => {
    formRef.value.resetFields();
  };

  //场所类型
  const locationOptions = ref();

  //检查类型相关
  const checkTypeOptions = ref();
  //区域相关
  const addressOptions = ref();
  const areaFieldNames = {
    label: 'name',
    value: 'id',
  };

  const organizers = ref({
    type: 0,
  });

  onMounted(async () => {
    const userData = await getInfo();
    userName.value = userData.userName;

    const res_check = await getCheckType();
    if (res_check.code === 0) {
      checkTypeOptions.value = res_check.data.map((item) => {
        return {
          label: item.configName,
          value: item.id,
        };
      });
    }
    const res_area = await getAreaList();
    if (res_area.code === 0) {
      addressOptions.value = res_area.data[0].children;
    }
    const place_type = await getPlaceType();
    if (place_type.code === 0) {
      locationOptions.value = place_type.data.map((item) => {
        return {
          label: item.configName,
          value: item.id,
        };
      });
    }

    if (route.query.id && route.query.placeId) {
      const data = await taskInfo(route.query.id);
      console.log(data);
      userName.value = data.checkerName;
      organizers.value = {
        type: 1,
      };
      formState.organizerId = data.organizerId;
      formState.organizerName = data.organizerName;
      formState.checkTypeId = data.checkTypeId;
      formState.checkTypeName = data.checkTypeName;
      formState.openPlaceInfo = data.openPlaceInfo;
      console.log(formState.openPlaceInfo.area);

      formState.openPlaceInfo.area = [
        data.openPlaceInfo.countyCode,
        data.openPlaceInfo.townCode,
      ] as any;

      boxTittle.value = '编辑任务';
    }

    const organizer = await organizerList(organizers.value);

    if (organizer.code === 0) {
      organizerOptions.value = organizer.data.map((item) => {
        return {
          label: item.userName,
          value: item.id,
        };
      });
    }
  });
</script>

<style lang="less" scoped>
  .task-box {
    background-color: #fff;

    &-top {
      &-tittle {
        padding: 0 0 16px;
        border-bottom: 1px solid rgb(240 240 240 / 100%);
        color: rgb(68 68 68 / 100%);
        font-size: 18px;
        font-weight: 700;
        line-height: 26px;
      }
    }

    .taskBox {
      &-tittle {
        display: flex;
        align-items: center;
        padding: 13px 0;

        &-left {
          height: 14px;
          margin-right: 7px;
          border: 1px solid #0f53ac;
          border-radius: 4px;
        }

        &-right {
          color: rgb(68 68 68 / 100%);
          font-size: 16px;
          font-weight: 400;
          line-height: 24px;
        }
      }
    }

    .bottomBox {
      height: 60px;
    }

    .bottomBtns {
      position: fixed;
      bottom: 0;
      width: calc(100% - 200px);
      padding: 8px 20px;
      border-top: 1px solid rgb(240 240 240 / 100%);
      background: rgb(255 255 255 / 100%);
      text-align: right;
    }
  }
</style>
